package org.acme.hibernate.orm.panache;


import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.listener.Event;
import com.alibaba.nacos.api.naming.listener.EventListener;
import com.alibaba.nacos.api.naming.listener.NamingEvent;
import com.alibaba.nacos.api.naming.pojo.Instance;
import io.quarkus.runtime.ShutdownEvent;
import io.quarkus.runtime.StartupEvent;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.event.Observes;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.microprofile.config.inject.ConfigProperty;

@Slf4j
public class AppInit {

    @ConfigProperty(name = "quarkus.http.port", defaultValue = "8080")
    int port;

    @ApplicationScoped
    public NamingService getNamingFactory() {
        try {
            return NamingFactory.createNamingService("127.0.0.1:8848");
        } catch (NacosException e) {
            log.error("nacos init have exception", e);
            return null;
        }
    }

    void onStart(@Observes StartupEvent ev, NamingService namingService) {
        try {
            Instance instance = new Instance();
            instance.setEnabled(true);
            instance.setIp("127.0.0.1");
            instance.setPort(port);
            instance.setServiceName("finance-backend");
            namingService.registerInstance("finance-backend", instance);
            namingService.subscribe("finance-backend", new EventListener() {
                @Override
                public void onEvent(Event event) {
                    NamingEvent namingEvent = (NamingEvent) event;
                    log.info("service change: {}", namingEvent.getServiceName());
                    Constant.NACOS_INSTANCE_MAP.put(namingEvent.getServiceName(), namingEvent.getInstances());
                }
            });

        } catch (NacosException e) {
            throw new RuntimeException(e);
        }
    }

    void onStop(@Observes ShutdownEvent ev, NamingService namingService) {
        log.info("The application is stopping...");
        Instance instance = new Instance();
        instance.setEnabled(true);
        instance.setIp("127.0.0.1");
        instance.setPort(port);
        instance.setServiceName("finance-backend");
        try {
            namingService.deregisterInstance("finance-backend", instance);
            namingService.unsubscribe("finance-backend", new EventListener() {
                @Override
                public void onEvent(Event event) {
                    NamingEvent namingEvent = (NamingEvent) event;
                    log.info("{} service cancel subscribe", namingEvent.getServiceName());
                }
            });
        } catch (NacosException e) {
            log.error("service stop have exception", e);
        }
    }

}
